#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to parse window_login.json and extract name, type, text fields.
If child array exists, it will also parse the child nodes.
"""

import json
import os
import sys


def extract_node_info(node):
    """
    Extract name, type, text from a node.
    If child or list array exists, recursively extract info from child nodes.
    """
    info = {
        "name": node.get("name", ""),
        "type": node.get("type", ""),
        "text": node.get("text", "")
    }
    
    # If child array exists, process child nodes
    if "child" in node:
        info["child"] = []
        for child_node in node["child"]:
            info["child"].append(extract_node_info(child_node))
    
    # If list array exists, process list nodes
    if "list" in node:
        info["list"] = []
        for list_node in node["list"]:
            info["list"].append(extract_node_info(list_node))
    
    return info


def parse_window_login(json_file_path, output_dir):
    """
    Parse window_login.json and save extracted info to a new JSON file.
    """
    # Read the JSON file
    with open(json_file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # Extract info from the root node
    extracted_info = extract_node_info(data)
    
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)
    
    # Save extracted info to a new JSON file
    output_file_path = os.path.join(output_dir, "parsed_window_login.json")
    with open(output_file_path, 'w', encoding='utf-8') as f:
        json.dump(extracted_info, f, ensure_ascii=False, indent=2)
    
    print(f"Successfully parsed {json_file_path} and saved to {output_file_path}")


def main():
    if len(sys.argv) != 3:
        print("Usage: python parse_window_login.py <input_json_file> <output_directory>")
        sys.exit(1)
    
    input_json_file = sys.argv[1]
    output_directory = sys.argv[2]
    
    if not os.path.exists(input_json_file):
        print(f"Error: {input_json_file} does not exist.")
        sys.exit(1)
    
    parse_window_login(input_json_file, output_directory)


if __name__ == "__main__":
    main()